import time

from uiautomator2 import Device

from le_engine.base import LittleEmpire
from le_engine.config import CommonConfig, IconName
from utils.logger import log


class Train:

    def __init__(self, le: LittleEmpire, event=None):
        self.le = le
        self.client: Device = self.le.get_client()

        self.re_try_kill_times = 0
        self.event = event

    def training(self):

        if not self.le.enter_train():
            return False, "进入训练场失败"

        while True:
            self.le.im.click_image(CommonConfig.img_path(IconName.xlc_refresh))

            if self.client(text="训练场中还有可以挑战的目标，是否确定刷新？").wait(timeout=CommonConfig.n_t_o):
                self.client.click(0.858, 0.157)

            elif self.client(textContains="已用光刷新次").wait(timeout=CommonConfig.n_t_o):
                log.info(f"训练场次数用完", extra={"pk": self.le.pk})
                self.client.click(0.858, 0.157)
                break

            if self.le.im.click_image(CommonConfig.img_path(IconName.xlc_6batch)) or self.le.im.click_image(CommonConfig.img_path(IconName.xlc_batch)):
                log.info("点击读取阵容", extra={"pk": self.le.pk})
                self.client.click(0.832, 0.334)
                log.info("选择刷训练场的阵容", extra={"pk": self.le.pk})
                time.sleep(1)
                if self.client(text="训练场").click_exists(timeout=CommonConfig.n_t_o):
                    if not self.client(text="训练场").wait(timeout=CommonConfig.n_t_o):
                        self.client.click(*CommonConfig.right_bottom_position)

                        if self.client(text="确认").click_exists(timeout=CommonConfig.n_t_o):
                            if self.client(text="总奖励").wait(timeout=CommonConfig.net_t_o):
                                self.le.im.click_image(CommonConfig.img_path(IconName.xlc_close))
            else:
                for i in range(3):
                    for j in range(2):
                        if self.event and self.event.is_set():
                            log.info("已停止刷训练场", extra={"pk": self.le.pk})
                            return False, None

                        log.info(f"选中第 {i+1} 排第 {j+1} 个", extra={"pk": self.le.pk})

                        p = self.client.xpath(
                            f'//*[@resource-id="com.camelgames.hogwarts:id/list"]/android.widget.LinearLayout[{i + 1}]/android.widget.LinearLayout[1]/android.widget.LinearLayout[{j + 1}]')
                        if p.exists:
                            p.click(timeout=CommonConfig.n_t_o)

                        if self.client(text="查看").wait(timeout=CommonConfig.n_t_o):
                            self.client.click(0.858, 0.157)
                            continue

                        if self.le.im.click_image(CommonConfig.img_path(IconName.fight)):
                            log.info("点击读取阵容", extra={"pk": self.le.pk})
                            if self.le.im.click_image(CommonConfig.img_path(IconName.read), max_retries=5):
                                log.info("选择刷训练场的阵容", extra={"pk": self.le.pk})
                                if self.client(text="训练场").click_exists(timeout=CommonConfig.n_t_o):
                                    if self.le.im.click_image(CommonConfig.img_path(IconName.confirm), max_retries=3):
                                        if self.le.im.click_image(CommonConfig.img_path(IconName.xlc_tiaoguo)):
                                            self.client(text="确定").click_exists(timeout=CommonConfig.n_t_o)
                                        elif not self.le.im.click_image(CommonConfig.img_path(IconName.xlc_2x)):
                                            self.client.click(*CommonConfig.right_bottom_position)

                                    if self.client(text="敌方损失部队:").wait(timeout=CommonConfig.t_t_o):
                                        self.client.click(0.652, 0.338)
                                        continue

                                    print(3434)
                        else:
                            if self.client(text="知道了").click_exists(CommonConfig.n_t_o):
                                self.client.click(0.858, 0.157)
                                self.client.click(0.858, 0.157)
                                continue
                            else:
                                self.client.click(0.858, 0.157)
                                self.client.click(0.858, 0.157)
                                continue
            log.info("完成一页", extra={"pk": self.le.pk})

            if self.client(textContains="恭喜你").wait(timeout=CommonConfig.n_t_o):
                self.client.click(0.626, 0.235)

        self.le.im.click_image(CommonConfig.img_path(IconName.xlc_close))
        return True, None

    def start(self):

        if not self.le.inter_game():
            return False, None

        try:
            ok, main_train = self.training()
        except Exception as e:
            return False, e
        else:
            if ok:
                self.le.enter_aux_castle()
                try:
                    ok_1, aux_train = self.training()
                except Exception as e:
                    return False, e
                return ok_1, aux_train
            else:
                return ok, main_train
